package com.lineage.server.timecontroller.server;

import com.lineage.config.Config;
import com.lineage.config.ConfigAlt;
import com.lineage.server.Shutdown;
import com.lineage.server.datatables.QuizSetTable;
import com.lineage.server.thread.GeneralThreadPool;
import com.lineage.server.world.World;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.TimeZone;
import java.util.TimerTask;
import java.util.concurrent.ScheduledFuture;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class ServerRestartTimer extends TimerTask {
  private static final Log _log = LogFactory.getLog(ServerRestartTimer.class);
  
  private ScheduledFuture<?> _timer;
  
  private static final ArrayList<Calendar> _restartList = new ArrayList<>();
  
  private static Calendar _restart = null;
  
  private static String _string = "yyyy/MM/dd HH:mm:ss";
  
  private static String _startTime = null;
  
  private static String _restartTime = null;
  
  public static String get_restartTime() {
    return _restartTime;
  }
  
  public static String get_startTime() {
    return _startTime;
  }
  
  public static boolean isRtartTime() {
    return (_restart != null && 
      _restart.getTimeInMillis() - System.currentTimeMillis() <= 600000L);
  }
  
  private static Calendar timestampToCalendar() {
    TimeZone _tz = TimeZone.getTimeZone(Config.TIME_ZONE);
    Calendar cal = Calendar.getInstance(_tz);
    return cal;
  }
  
  public void start() {
    if (Config.AUTORESTART == null)
      return; 
    Calendar cals = timestampToCalendar();
    if (_startTime == null){
		final String nowDate = new SimpleDateFormat(_string).format(cals.getTime());
		_startTime = nowDate;
	}
    if (Config.AUTORESTART != null) {
      String HH = (new SimpleDateFormat("HH")).format(cals.getTime());
      int HHi = Integer.parseInt(HH);
      String mm = (new SimpleDateFormat("mm")).format(cals.getTime());
      int mmi = Integer.parseInt(mm);
      String[] autorestart;
      int length = (autorestart = Config.AUTORESTART).length;
      int i = 0;
      while (i < length) {
        String hm = autorestart[i];
        String[] hm_b = hm.split(":");
        String hh_b = hm_b[0];
        String mm_b = hm_b[1];
        int newHH = Integer.parseInt(hh_b);
        int newMM = Integer.parseInt(mm_b);
        Calendar cal = timestampToCalendar();
        int hourdistance = -1;
        int xhh = newHH - HHi;
        int minutedistance = -1;
        int xmm = newMM - mmi;
        if (xhh >= 1) {
          hourdistance = xhh;
          minutedistance = xmm;
        } else if (xhh == 0) {
          if (xmm >= 1) {
            hourdistance = xhh;
            minutedistance = xmm;
          } else {
            hourdistance = 24 - HHi + newHH;
            minutedistance = xmm;
          } 
        } else {
          hourdistance = 24 - HHi + newHH;
          minutedistance = xmm;
        } 
        cal.add(10, hourdistance);
        cal.add(12, minutedistance);
        _restartList.add(cal);
        i++;
      } 
      Iterator<Calendar> iterator = _restartList.iterator();
      while (iterator.hasNext()) {
        Calendar tmpCal = iterator.next();
        if (_restart == null) {
          _restart = tmpCal;
          continue;
        } 
        if (!tmpCal.before(_restart))
          continue; 
        _restart = tmpCal;
      } 
    } 
    String restartTime = _restartTime = (new SimpleDateFormat(_string))
      .format(_restart.getTime());
    int timeMillis = 60000;
    this._timer = GeneralThreadPool.get().scheduleAtFixedRate(this, 60000L, 60000L);
  }
  
  public void run() {
    try {
      startCommand();
    } catch (Exception e) {
      _log.error("自动重启时间轴异常重启", e);
      GeneralThreadPool.get().cancel(this._timer, false);
      ServerRestartTimer restartTimer = new ServerRestartTimer();
      restartTimer.start();
    } 
  }
  
  private void startCommand() {
    if (Config.AUTORESTART != null) {
      Calendar cals = Calendar.getInstance();
      if (ConfigAlt.QUIZ_SET_RESET_TIME != null && ConfigAlt.QUIZ_SET_RESET_TIME.before(cals)) {
        if (ConfigAlt.QUIZ_SET_SWITCH) {
          QuizSetTable.getInstance().updateQuizToNext();
          QuizSetTable.getInstance().updateQuizInfo();
          QuizSetTable.getInstance().updateAllPcQuizSet();
          World.get().broadcastServerMessage("\\fX【每日一题】今日题目已自动更新完成，快来赚奖品喔！");
        } 
        ConfigAlt.QUIZ_SET_RESET_TIME = null;
      } 
      cals.setTimeInMillis(System.currentTimeMillis());
      if (_restart.before(cals))
        Shutdown.getInstance().startShutdown(null, 300, true); 
    } 
  }
}
